/*
 * button.c
 * Project 4
 * Nicole Ang (nang1@asu.edu)
 * Bijan Fakhri (bfakhri@asu.edu)
 * CSE 325: Embedded Microprocessor Systems
 * Spring 2013
 */
#include "button.h"

int tempoDir; //direction tempo is changing
				//0 speeding up, 1 going down
int currentBeat;

void gpt_init(){
	//configure port TA pin 0 for primary (GPT) function
	MCF_GPIO_PTAPAR |= MCF_GPIO_PTAPAR_PTAPAR0(1);
	
	//clear GPTIOS[IOS0] to enable channel 0 for input capture
	MCF_GPT_GPTIOS &= ~MCF_GPT_GPTIOS;
	
	//configure GPTCTLS2[EDG0] to capture high-to-low signal changes, i.e. button presses
	MCF_GPT_GPTCTL2 |= MCF_GPT_GPTCTL2_EDG0B;
	
	//clear GPTDDR[DDRT0] so the channel 0 pin is an input pin
	MCF_GPT_GPTDDR &= ~MCF_GPT_GPTDDR_DDRT0;
	
	//set GPTIE[C0I] to enable channel 0 interrupts
	MCF_GPT_GPTIE |= MCF_GPT_GPTIE_CI0;
	
	//set GPTSCR1[GPTEN] to enable the GPT
	//configure the INTC module to recognized interrupts from GPT channel 0
	intcr_config(44, 1, 7, gpt0_isr);
	
	//intially tempo will go up, initially 60BPM
	tempoDir = 0;
	currentBeat = 60;
}
__declspec(interrupt) void gpt0_isr(){
	/* Clear the GPT channel 0 interrupt request flag. */
	MCF_GPT_GPTFLG1 |= MCF_GPT_GPTFLG1_CF0;

	/* Do whatever you need to do to service the GPT channel. */
	if(tempoDir)
		currentBeat = currentBeat - 10;
	else
		currentBeat = currentBeat + 10;
	
	if(currentBeat == 60 || currentBeat == 120)
		tempoDir = (~tempoDir) & 0x1;//switch direction
	
	setTempo(currentBeat);	
}